import fs from "node:fs/promises";
import { sleep } from "./utils/index.js";
import {getNewPage, launchChrome, closeChrome} from "./utils/chrome.js";


const content = await fs.readFile('./input.txt', 'utf8');

const [serverUrl, ...rows] = content.split('\n');

if(!serverUrl.startsWith('http')) {
  throw new Error(`客服地址无效`);
}

await launchChrome();
const page = await getNewPage();

await page.goto(serverUrl, {
  // waitUntil: 'networkidle0', // 等待网络空闲（推荐）
  waitUntil: 'networkidle2',
  timeout: 60000, // 超时时间，默认 30 秒，可以调大
});
for (const row of rows) {
  const cardNo = row.trim();
  if(cardNo) {
    const item = [cardNo];
    try {
      const msg = await activateCard(cardNo);
      console.log(`成功，${msg}`)
      item.push('成功');
    }catch(err){
      const msg = err.message.replaceAll('\n', '')
      console.error(`失败，${msg}`)
      item.push('失败');
      item.push(msg);
    }
    await fs.appendFile('./output.txt', item.join('----') + '\n', 'utf8');
  }
}
await closeChrome();

async function activateCard(row) {
  await page.type('.Composer .Input', '激活');
  console.log('输入[激活]')
  await page.click('.Composer-sendBtn');
  console.log('点击[发送]');
  await sleep(1500);
  const buttons = await page.$$('.ScrollView-scroller .ScrollView-item');

  for (const button of buttons) {
    const text = await page.evaluate(el => el.innerText.trim(), button);
    if (text === '星礼包') {
      console.log('点击[星礼包]');
      await button.click();
      break; // 找到后就结束循环
    }
  }
  await sleep(1500);
  await page.type('.CUFInput', row);
  console.log('输入[卡号]' + row)
  await sleep(1000);
  await page.click('.Popup-footer .Btn');
  console.log('点击[提交]');
  await sleep(1500);
  const messageList = await page.$$('.Message.left .Bubble.text');
  const lastMsgEl = messageList[messageList.length - 1];
  const msg = await page.evaluate(el => el.innerText.trim(), lastMsgEl);
  if(msg.includes('您的星礼包已激活')) {
    return msg
  }else {
    throw new Error(msg);
  }
}
